<?php
/**
 * phpwell import class
 *
 * Provides organized interface for loading phpwell modules
 *
 *
 * @package     phpwell
 * @author      Tom Atwell <klenwell@gmail.com>
 * @copyright   Copyright 2010, Tom Atwell <klenwell@gmail.com>
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @link        http://klenwell.com/is
 *
 * <code>
 * require_once 'phpwell/import.php';
 * import_well('web/client');
 * </code>
 */

/**
 * constants
 */
define('PHPWELL_VERSION', 0.1);
define('PHPWELL_ROOT', dirname(__FILE__));
define('PHPWELL_CONF', sprintf('%s/%s', PHPWELL_ROOT, 'conf'));
define('PEAR_ROOT', sprintf('%s/%s', PHPWELL_ROOT, 'pear'));
define('PHPWELL_LOG_PATH', sprintf('/tmp/phpwell-%s.log', date('Ymd')));

define('IS_CLI_WELL', php_sapi_name() == 'cli');
define('IS_BROWSER_WELL', isset($_SERVER['HTTP_USER_AGENT']));

/**
 * function to import a library file or module.  a glorified wrapper for
 * require_once.
 */
function import_well($mod_path) {
    $ext = pathinfo($mod_path, PATHINFO_EXTENSION);
    if ( empty($ext) ) {
        $ext = 'php';
        $infer_file = sprintf('%s.%s', $mod_path, $ext);
        $infer_mod  = sprintf('%s/import.%s', $mod_path, $ext);

        if ( is_importable_well($infer_file) ) {
            $mod_path = $infer_file;
        }
        elseif ( is_importable_well($infer_mod) ) {
            $mod_path = $infer_mod;
        }
        elseif ( strtolower($mod_path) == 'pear' ) {
            $mod_path = 'pear/PEAR.php';
        }
    }
    require_once $mod_path;
}

function import_config($conf) {
    $ConfigDict = array();

    $ext = 'php';
    $infer_file = sprintf('conf/%s.%s', $mod_path, $ext);

    if ( file_exists($infer_file) ) {
        $conf = $infer_file;
    }

    require_once $conf;
    return $ConfigDict;
}

/**
 * file_exists that checks include path
 * @link http://www.php.net/manual/en/function.file-exists.php#93253
 */
function is_importable_well($path) {

    # check for absolute path
    if ( realpath($path) == $path ) {
        return $path;
    }

    # treat as relative path
    $paths = explode(PATH_SEPARATOR, get_include_path());
    foreach ( $paths as $dir ) {
        $dir = ( substr($dir, -1) == DIRECTORY_SEPARATOR )
            ? $dir
            : $dir.DIRECTORY_SEPARATOR;
        $fullpath = $dir.$path;
        if (file_exists($fullpath)) {
            return $fullpath;
        }
    }

    return false;
}

/**
 * simplified function for extending the include path
 */
function extend_include_path_well($path) {
    $PathList = explode(PATH_SEPARATOR, get_include_path());
    if ( !in_array($path, $PathList) ) {
        $PathList[] = $path;
    }
    $include_path = implode(PATH_SEPARATOR, $PathList);
    ini_set('include_path', $include_path);
}

/**
 * simple log function
 */
function log_well($message, $level='debug') {

    $mf = "%-20s  %-8.8s %s\n";
    $m = sprintf($mf, date('Y-m-d H:i:s'), strtoupper($level), $message);

    if ( ! defined('PHPWELL_LOG_PATH') || is_null(PHPWELL_LOG_PATH) ) {
        return;
    }

    $fh = fopen(PHPWELL_LOG_PATH, 'a');
    fwrite($fh, $m);
    fclose($fh);
    return;
}

/**
 * extend the include path to include phpwell and pear directories
 */
extend_include_path_well(PHPWELL_ROOT);
extend_include_path_well(PEAR_ROOT);

/**
 * main section: runs some debug code if this file is invoked directly in
 * browser or from command line
 */
$is_main_cli = isset($_SERVER['argv'][0]) && (realpath($_SERVER['argv'][0]) == __FILE__);
$is_main_browser= isset($_SERVER['SCRIPT_FILENAME']) && ($_SERVER['SCRIPT_FILENAME'] == __FILE__);
if ( $is_main_cli || $is_main_browser ) {

    import_well('pear');
    import_well('Net/URL2');

    $outputf = <<<HDOC
phpwell library v%s
%s

php version  : %s
include path : %s
log path     : %s

SERVER
------
%s

HDOC;

    $output = sprintf($outputf,
                      PHPWELL_VERSION,
                      __FILE__,
                      PHP_VERSION,
                      get_include_path(),
                      PHPWELL_LOG_PATH,
                      print_r($_SERVER,1));

    log_well('log test: import.php called directly');

    if ( $cli_request ) {
        print $output;
    }
    else {
        printf('<pre>%s</pre>', $output);
    }
}
